import React, { useEffect } from 'react';
import { Button, DatePicker, Select, Space, Spin } from 'antd';
import _ from 'lodash';
import moment from 'moment';

import { useTRState } from '#/utils/trHooks.jsx';
import { TjSegmented, TjChart, TjSelect } from '@/pages/ETrade/components';
import { queryStationAndNode, queryNodePriceComparison } from '../../services.js';
import MyModal from './MyModal';
import styles from './index.less';
import { getCssVariableValue } from '@/utils/utils';
import { useThemeChange } from '@/hooks';

const getDateRange = () => {
  return [moment().add(-3, 'day'), moment().add(-1, 'day')];
};

export default ({ power }) => {
  /**
   * 从树形结构中提取所有节点的value和stationName配对
   * @param {Array} data - 树形结构数据
   * @returns {Object} - {value: stationName}格式的映射对象
   */
  const extractStationMap = (data) => {
    const result = {};

    // 递归遍历函数
    const traverse = (nodes) => {
      nodes.forEach((node) => {
        // 将当前节点的value和stationName配对
        if (node.value !== undefined && node.stationName !== undefined) {
          result[node.value] = node.stationName;
        }

        // 递归处理子节点
        if (node.children && Array.isArray(node.children)) {
          traverse(node.children);
        }
      });
    };

    // 启动遍历
    traverse(data);
    return result;
  };

  const getDefaultData = (marketItem = {}) => {
    const stationOptions = marketItem.children || [];
    let baseData = {
      dates: getDateRange(),
      stationLaebl: '全部交易单元',
      marketItem,
      stationIds: _.flattenDeep(stationOptions?.map((a) => a?.children?.map((x) => x.value))),
      stationMap: extractStationMap(stationOptions),
      stationOptions,
      formValue: {
        marketId: marketItem.value,
      },
    };
    if (marketItem.marketId === 'PDBLJ' || marketItem.marketId === 'PXBNX') {
      baseData = { ...baseData, keySup: 'dayActual', keySub: 'adjustAhead', pointKey: '96' };
    } else {
      baseData = {
        ...baseData,
        keySup: 'provincialRealtimeClearing',
        keySub: 'PriceUnadjusted',
        pointKey: 'ninetySixMap',
      };
    }
    return baseData;
  };

  const [state, setState] = useTRState({
    formValue: {}, // 已用表单
    marketItem: {}, // 交易中心信息
    stationIds: [], // 交易单元id集合
    stationOptions: [], // 公司 > 交易单元
    nodeMap: {}, // 交易单元: 节点 映射
    loadingNodeMap: false,
    // result
    loading: true,
    dataSource: [],
    chartData: {},
    stationMap: {},
    ...getDefaultData(power[0]),
    // 触发fetch更新
    isFetch: false,
  });
  const { theme } = useThemeChange();

  useEffect(() => {
    _onFinish();
  }, [state.isFetch]);

  const getNodeMap = async (id) => {
    // 获取交易单元对应节点
    if (!id) return;
    setState({ loadingNodeMap: true });
    let nodeMap = { ...state.nodeMap };
    const res = await queryStationAndNode({ provinceId: id });
    const resList = res?.data?.stationNodeList || [];
    resList.map((x) => {
      nodeMap[x.stationName] = x.nodeNameAlias;
    });
    setState({
      nodeMap,
      loadingNodeMap: false,
    });
  };

  const onChangeMarket = (marketItem) => {
    // 交易中心改变
    let stationIds = [];
    const stationOptions = marketItem?.children || [];
    stationIds = _.flattenDeep(stationOptions?.map((a) => a?.children?.map((x) => x.value)));

    state.marketItem = marketItem;
    state.stationIds = stationIds;
    setState({
      ...getDefaultData(marketItem),
    });
    getNodeMap(marketItem?.provinceId);
  };

  const onClickStations = async () => {
    const result = await MyModal.show({
      title: '交易单元',
      value: state.stationIds,
      treeData: state.stationOptions,
      nodeMap: state.nodeMap,
    });

    if (result?.index === 1 && result.checkedKeys.length) {
      setState({
        stationIds: result.checkedKeys,
        stationLaebl: result.selected,
      });
    }
    MyModal.dismiss();
  };

  const _onFinish = async () => {
    // 查询
    let formValue = {};
    formValue = {
      startDate: state.dates[0].format('YYYY-MM-DD'),
      endDate: state.dates[1].format('YYYY-MM-DD'),
      provinceId: state.marketItem.provinceId,
      marketId: state.marketItem.value,
      stationIds: [...state.stationIds],
      stateTime: state.keySup,
      stateAdjust: state.keySub,
      type: state.pointKey,
    };
    setState({
      formValue,
      loading: true,
    });
    const res = await queryNodePriceComparison(formValue);
    if (formValue.marketId === 'PDBLJ' || formValue.marketId === 'PXBNX') {
      state.dataSource = res?.data?.data || [];
    } else {
      state.dataSource = res?.data?.dataCompareMap || [];
    }
    setState({
      dataSource: state.dataSource,
      loading: false,
    });
  };

  const _onReset = () => {
    // 重置
    setState({
      ...getDefaultData(power[0]),
      isFetch: !state.isFetch,
    });
  };

  /** renders */
  const setSeries = (dataList) => {
    const { xAxis, ...dataSource } = dataList;
    return Object.entries(dataSource).map(([name, data]) => ({
      type: 'line',
      name: state.stationMap[name] || name,
      data: data.map((num) => {
        return _.isNil(Number(num)) ? '-' : _.round(Number(num), 2).toFixed(2);
      }),
    }));
  };
  const getChartOption = () => {
    // 以场站为系列，时间为X维度，筛选条件对应Y取值
    let seriesMap = {};
    let xAxisData = [];
    let series = [];
    const dataKey = state.keySup + state.keySub; // 日前or实时 + 修正前or修正后 拼接取值key
    if (state.formValue.marketId === 'PDBLJ' || state.formValue.marketId === 'PXBNX') {
      xAxisData = state.dataSource?.xAxis || [];
      series = setSeries(state.dataSource);
    } else {
      state.dataSource.map((x, idx) => {
        let dataMap = x?.[state.pointKey];
        Object.keys(dataMap).map((sId, sIdx) => {
          let seriesData = [];
          const dayList = dataMap[sId] || [];
          dayList.map((x) => {
            seriesData.push(x[dataKey]);
            if (sIdx === 0) {
              const xItem = moment(`${x.date} ${x.xAxis}`).format('YYYYMMDD HHmm');
              xAxisData.push(xItem);
            }
          });
          if (idx === 0) {
            seriesMap[sId] = {
              name: dayList?.[0]?.stationName,
              data: [],
              type: 'line',
            };
          }
          if (seriesMap[sId]) {
            seriesMap[sId].data = seriesMap[sId].data.concat(seriesData);
          }
        });
      });
      series = Object.values(seriesMap);
    }

    return {
      grid: { top: 48, left: 48, right: 0, bottom: 75 },
      series,
      tooltip: {
        enterable: true,
        extraCssText: 'max-height: 75%; overflow: hidden scroll;',
      },
      legend: {
        textStyle: {
          color: getCssVariableValue('--chart-legend-color'),
        },
      },
      xAxis: [
        {
          type: 'category',
          data: xAxisData,
          formatter: (v) => v.slice(4),
          axisLabel: {
            color: getCssVariableValue('--chart-font-color'),
          },
          axisLine: {
            lineStyle: {
              type: 'solid',
              color: getCssVariableValue('--chart-x-line'),
            },
          },
          axisTick: {
            lineStyle: {
              color: getCssVariableValue('--chart-y-line'),
            },
          },
          axisPointer: {
            type: 'line',
            lineStyle: {
              color: getCssVariableValue('--chart-x-line'),
            },
          },
        },
      ],
      yAxis: [
        {
          type: 'value',
          name: '元/MWh',
          axisLabel: {
            color: getCssVariableValue('--chart-font-color'),
          },
          axisTick: {
            lineStyle: {
              color: getCssVariableValue('--chart-y-line'),
            },
          },
          splitLine: {
            lineStyle: {
              color: getCssVariableValue('--chart-y-line'),
            },
          },
        },
      ],
      dataZoom: [
        {
          type: 'slider',
          bottom: 26,
          start: 0,
          right: 8,
          end: 100,
          height: 20,
          show: true,
          backgroundColor: getCssVariableValue('--bg-form'),
          dataBackground: {
            dataBackground: {
              areaStyle: { opacity: 0 },
              lineStyle: { opacity: 0 },
            },
          },
          selectedDataBackground: {
            areaStyle: {
              color: getCssVariableValue('--font-primary'),
              opacity: 0.15,
            },
            lineStyle: { color: 'transparent' },
          },
          borderColor: 'transparent',
          handleStyle: {
            color: getCssVariableValue('--bg-form'),
            borderColor: getCssVariableValue('--bd'),
          },
          brushSelect: false,
          showDetail: false,
        },
      ],
    };
  };

  useEffect(() => {
    setTimeout(() => {
      const chartData = getChartOption();
      setState({ chartData });
    }, 1);
  }, [state.dataSource, theme]);

  return (
    <>
      <div className={styles.head}>
        <Space size={16} wrap>
          <Select
            style={{ width: 200 }}
            value={state.marketItem.value}
            options={power}
            optionFilterProp="label"
            showSearch
            showArrow
            onChange={(v, option) => onChangeMarket(option)}
            getPopupContainer={(e) => e.parentNode}
          />
          <DatePicker.RangePicker
            style={{ width: 216 }}
            value={state.dates}
            separator="-"
            format={'YYYYMMDD'}
            disabledDate={(v) => v > moment()}
            allowClear={false}
            onChange={(dates) => setState({ dates })}
            getPopupContainer={(e) => e.parentNode}
          />
          <Select
            style={{ width: 200 }}
            value={state.stationLaebl}
            disabled={state.loadingNodeMap}
            open={false}
            onClick={onClickStations}
          />
          <TjSegmented
            value={state.pointKey}
            options={[
              {
                label: '24',
                value:
                  state.formValue.marketId === 'PDBLJ' || state.formValue.marketId === 'PXBNX'
                    ? '24'
                    : 'twentyFourMap',
              },
              {
                label: '96',
                value:
                  state.formValue.marketId === 'PDBLJ' || state.formValue.marketId === 'PXBNX'
                    ? '96'
                    : 'ninetySixMap',
              },
            ]}
            onChange={(pointKey) => setState({ pointKey })}
          />
          <Space size={16}>
            <Button
              style={{ width: 98, height: 32 }}
              type="primary"
              disabled={state.loading || state.loadingNodeMap}
              onClick={_onFinish}
            >
              查询
            </Button>
            <Button style={{ width: 98, height: 32 }} ghost onClick={_onReset}>
              重置
            </Button>
          </Space>
        </Space>
        <Space size={16} wrap>
          <TjSegmented
            value={state.keySup}
            options={[
              {
                label: '日前',
                value:
                  state.formValue?.marketId === 'PDBLJ' || state.formValue?.marketId === 'PXBNX'
                    ? 'dayAhead'
                    : 'provincialDayaheadClearing',
              },
              {
                label: '实时',
                value:
                  state.formValue?.marketId === 'PDBLJ' || state.formValue?.marketId === 'PXBNX'
                    ? 'dayActual'
                    : 'provincialRealtimeClearing',
              },
            ]}
            // 修改当前值时直接触发查询
            onChange={(keySup) => setState({ keySup, isFetch: !state.isFetch })}
          />
          {state.formValue?.marketId !== 'PDBLN' && (
            <TjSegmented
              value={state.keySub}
              options={[
                {
                  label: state.formValue?.marketId == 'PXBMX' ? '测算' : '修正前',
                  value:
                    state.formValue?.marketId === 'PDBLJ' || state.formValue?.marketId === 'PXBNX'
                      ? 'adjustAhead'
                      : 'PriceUnadjusted',
                },
                {
                  label: state.formValue?.marketId == 'PXBMX' ? '结算' : '修正后',
                  value:
                    state.formValue?.marketId === 'PDBLJ' || state.formValue?.marketId === 'PXBNX'
                      ? 'adjustAfter'
                      : 'Price',
                },
              ]}
              // 修改当前值时直接触发查询
              onChange={(keySub) => setState({ keySub, isFetch: !state.isFetch })}
            />
          )}
        </Space>
      </div>
      <div className={styles.main}>
        <Spin spinning={state.loading}>
          <TjChart option={state.chartData} style={{ height: 350 }} />
        </Spin>
      </div>
    </>
  );
};
